package protocol.data;

import protocol.Frame;

/**
 * A reply packet
 * @date 27.5.2011
 */
public class ReplyPacket implements Frame {
	
	private byte type;
	private int sequenceNumber;
	
	public byte getType() {
		return this.type;
	}
	
	public void setType(byte type) {
		this.type = type;
	}
	
	public int getSequenceNumber() {
		return this.sequenceNumber;
	}

	public void setSequenceNumber(int sequenceNumber) {
		this.sequenceNumber = sequenceNumber;
	}

	/**
	 * Constructor
	 */
	public ReplyPacket() {
	}
	
	/**
	 * Constructor
	 * @param bytes Supplied for the method parse().
	 */
	public ReplyPacket(byte[] bytes) {
		this.parse(bytes);
	}
	
	/**
	 * The defined packet format is:
	 * | 1 byte | 4 bytes         |
	 * |--------|-----------------|
	 * | Type   | Sequence number |
	 * |--------------------------|
	 */
	public byte[] build() {
		byte[] data = new byte[5];
		/**
		 * Set the type field in the packet
		 */
		data[0] = this.getType();
		/**
		 * Set the sequence number to the packet
		 */
		data[1] = (byte)(this.getSequenceNumber() >> 24);
		data[2] = (byte)(this.getSequenceNumber() >> 16);
		data[3] = (byte)(this.getSequenceNumber() >> 8);
		data[4] = (byte)(this.getSequenceNumber() & 0xFF);
		return data;
	}

	/**
	 * The defined packet format is:
	 * | 1 byte | 4 bytes         |
	 * |--------|-----------------|
	 * | Type   | Sequence number |
	 * |--------------------------|
	 */
	public void parse(byte[] bytes) {
		/**
		 * Save the reply type
		 */
		this.setType(bytes[0]);
		/**
		 * Save the sequence number
		 */
		int sequenceNumber = 0;
		sequenceNumber |= (bytes[1] << 23);
		sequenceNumber |= (bytes[2] << 15);
		sequenceNumber |= (bytes[3] << 7);
		sequenceNumber |= (bytes[4]);
		this.setSequenceNumber(sequenceNumber);
	}

}